//
//  PersonInfoViewController.m
//  ForestPack
//
//  Created by 郑洲 on 2018/7/5.
//  Copyright © 2018年 郑洲. All rights reserved.
//

#import "PersonInfoViewController.h"
#import "PersonInfoModel.h"
#import "InfomationViewController.h"

@interface PersonInfoViewController ()<UITableViewDelegate, UITableViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate,ChangeIntroDelegate>

@property (nonatomic, strong) UIImageView   *headImage;
@property (nonatomic, strong) BaseTableView *tableView;

@property (nonatomic,strong)  NSArray<PersonInfoPicsModel *>     * picsArray;
@property (nonatomic,strong)  PersonInfoModel                    * personInfoModel;
@property (nonatomic, strong) NSArray                            * valuesArray;
@property (nonatomic,strong)  NSArray                            * titlesArray;

@property (nonatomic,copy)    NSString                           * leftImgUrl;
@property (nonatomic,copy)    NSString                           * rightImgUrl;

@property (nonatomic, strong) UIImagePickerController *pickerController;

@end

@implementation PersonInfoViewController

- (NSArray *)picsArray
{
    if (_picsArray == nil) {
        _picsArray = [[NSArray alloc] init];
    }
    return _picsArray;
}

- (NSArray *)valuesArray
{
    if (_valuesArray == nil) {
        _valuesArray = [[NSArray alloc] init];
    }
    return _valuesArray;
}

- (NSArray *)titlesArray
{
    if (_titlesArray == nil) {
        _titlesArray = [[NSArray alloc] init];
    }
    return _titlesArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"个人资料";
    self.view.backgroundColor = TABLEVIEW_BACKGROUNDCOLOR;
    
    [self initData];
    self.tableView = [[BaseTableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    
    [self setRefreshTableView];
    [self getUserInfoData];
    
//    [self setRightButton:nil title:@"保存" target:self action:@selector(save)];
    
    self.pickerController = [[UIImagePickerController alloc] init];
    self.pickerController.delegate = self;
    
    NSString *token =  [FPLoginAndRegisterTools getToken];
    NSLog(@"%@************************",token);
}

- (void)initData
{
    self.titlesArray = @[@[@"头像"],@[@"昵称",@"等级"],@[@"企业名称",@"所在地址",@"身份",@"手机号码"]];
    self.valuesArray = @[@[@""],@[@"",@""],@[@"",@"",@"",@""]];
}

- (void)save {
    
}

#pragma mark - 刷新数据
- (void)setRefreshTableView
{
    /** 为了避免 block 的循环引用导致内存泄漏  要使用__weakSelf 来代替self */
//    __weak typeof(self) weakSelf = self;
    WeakObj(self);
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [selfWeak getUserInfoData];
    }];
}

-(void)getUserInfoData
{
    WeakObj(self);
    NSString * url =[NSString stringWithFormat:@"%@app/user_info",REQUESTHEADER];
    NSDictionary * parames = @{@"token":[FPLoginAndRegisterTools getToken]};
    [HttpManager showWait];
    [HttpManager postHttpRequestByPost:url andParameter:parames success:^(id successResponse) {
        [HttpManager hideWait];
        [self.tableView.mj_header endRefreshing];
        NSDictionary * dict = successResponse;
        if (dict == nil) {
            return ;
        }
        PersonInfoModel * personInfoM= [[PersonInfoModel alloc] initWithDictionary:dict error:nil];
        
        if ([personInfoM.status isEqualToString:@"1"]) {
            [HttpManager hideWait];
            selfWeak.personInfoModel = personInfoM;
            selfWeak.picsArray = personInfoM.pics;
            [selfWeak updateData:personInfoM];
            [selfWeak.tableView reloadData];
        }else{
            [HttpManager showNoteMsg:personInfoM.msg];
        }
    } andFailure:^(id failureResponse) {
        [selfWeak.tableView.mj_header endRefreshing];
        [HttpManager showFail];
    }];
}

- (void)updateData:(PersonInfoModel *)personInfoModel
{
    NSString * realname = [personInfoModel.data valueForKey:@"realname"] == nil ? @"" : [personInfoModel.data valueForKey:@"realname"];
    NSString * vip = [personInfoModel.data valueForKey:@"vip"] == nil ? @"" : [personInfoModel.data valueForKey:@"vip"];
    NSString * company_address = [[personInfoModel.data valueForKey:@"company_address"] class] == [NSNull class] ? @"" : [personInfoModel.data valueForKey:@"company_address"];
    NSString * type = [NSString stringWithFormat:@"%@",[personInfoModel.data valueForKey:@"type"] ] == nil ? @"" : [NSString stringWithFormat:@"%@",[personInfoModel.data valueForKey:@"type"]];
    
    NSString * qualification_pic = @"";
    NSString * qualification_pic2 = @"";
    NSString * typeName = @"";
    NSString * typeDetail = @"";
    if ([type isEqualToString:@"1"]) {
        typeName = @"真实姓名";
        typeDetail = @"设计师";
        qualification_pic = [personInfoModel.pics[0] valueForKey:@"qualification_pic"] == nil ? @"" : [personInfoModel.pics[0] valueForKey:@"qualification_pic"];
        qualification_pic2 = [personInfoModel.pics[1] valueForKey:@"qualification_pic"] == nil ? @"" : [personInfoModel.pics[1] valueForKey:@"qualification_pic"];
        self.leftImgUrl = qualification_pic;
        self.rightImgUrl = qualification_pic2;
    }else{
        typeName = @"企业名称";
        typeDetail = @"设计师/客户经理/终端客户";
        NSString * qualification_pic = [personInfoModel.pics[0] valueForKey:@"qualification_pic"] == nil ? @"" : [personInfoModel.pics valueForKey:@"qualification_pic"];
        self.leftImgUrl = qualification_pic;
        self.rightImgUrl = @"";
    }
    NSString * telephone = [personInfoModel.data valueForKey:@"telephone"] == nil ? @"" : [personInfoModel.data valueForKey:@"telephone"];
//    NSString * person_img = [personInfoModel.data valueForKey:@"person_img"] == nil ? @"" : [personInfoModel.data valueForKey:@"person_img"];
    NSString * person_img = [[personInfoModel.data valueForKey:@"person_img"] class] == [NSNull class] ? @"" : [personInfoModel.data valueForKey:@"person_img"];
    
    
    
    self.titlesArray = @[@[@"头像"],@[@"昵称",@"等级"],@[typeName,@"所在地址",@"身份",@"手机号码"]];
    self.valuesArray = @[@[person_img],@[realname,vip],@[realname,company_address,typeDetail,telephone]];

    [self.tableView reloadData];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (section) {
        case 0:
            return 1;
            break;
        case 1:
            return 2;
            break;
        case 2:
            return 4;
            break;
        default:
            return 1;
            break;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        static NSString *cellId = @"headImage";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            
            _headImage = [[UIImageView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - ScreenX375(62), ScreenX375(6), ScreenX375(32), ScreenX375(32))];
            _headImage.clipsToBounds = YES;
            _headImage.layer.cornerRadius = ScreenX375(16);
            
            [cell addSubview:_headImage];
        }
        cell.textLabel.text = self.titlesArray[indexPath.section][indexPath.row];
        cell.textLabel.font = Kfont(14);
        
        NSString * imageUr = self.valuesArray[indexPath.section][indexPath.row];
        if (imageUr.length > 0) {
            [_headImage sd_setImageWithURL:[NSURL URLWithString:imageUr] placeholderImage:[UIImage imageNamed:@"头部背景"]];
        }else{
            _headImage.image = [UIImage imageNamed:@"头部背景"];
        }
        return cell;
    }else if (indexPath.section == 1 || indexPath.section == 2) {
        static NSString *cellId = @"otherCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellId];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            if (!(indexPath.section == 1 && indexPath.row == 1)) {
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            }
        }
        cell.textLabel.text = self.titlesArray[indexPath.section][indexPath.row];
        cell.textLabel.font = Kfont(14);
        cell.detailTextLabel.text = self.valuesArray[indexPath.section][indexPath.row];
        cell.detailTextLabel.font = Kfont(14);
        return cell;
    }else {
        static NSString *cellId = @"imageCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        UIImageView *leftImg = [[UIImageView alloc] initWithFrame:CGRectMake(ScreenX375(10), ScreenX375(10), ScreenX375((SCREEN_WIDTH - 20)/2), ScreenX375(110))];
        
        [cell addSubview:leftImg];
        UIImageView *rightImg = [[UIImageView alloc] initWithFrame:CGRectMake(ScreenX375(SCREEN_WIDTH - 120), ScreenX375(10), ScreenX375((SCREEN_WIDTH - 20)/2), ScreenX375(110))];
        [cell addSubview:rightImg];
        cell.textLabel.text = @"营业执照/身份证正反面";
        cell.textLabel.textColor = [UIColor lightGrayColor];
        // 自定义 cell
        if ([[self.personInfoModel.data valueForKey:@"type"] integerValue] == 1) {
            // 展示 身份证正反面
            [leftImg sd_setImageWithURL:[NSURL URLWithString:self.leftImgUrl]];
            [rightImg sd_setImageWithURL:[NSURL URLWithString:self.rightImgUrl]];
        }else{
             // 展示 营业执照
            [leftImg sd_setImageWithURL:[NSURL URLWithString:self.rightImgUrl]];
        }
        
        
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 3) {
        return ScreenX375(140);
    }
    return ScreenX375(44);
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return ScreenX375(10);
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, ScreenX375(10))];
    view.backgroundColor = TABLEVIEW_BACKGROUNDCOLOR;
    return view;
}

//- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//    if (indexPath.section == 1) {
//        if (indexPath.row == 0) {
//            InfomationViewController *vc = [[InfomationViewController alloc] init];
//            vc.changeIntroDelegate = self;
//            vc.type = @"0";
//            [self.navigationController pushViewController:vc animated:YES];
//        }else if (indexPath.row == 1) {
//            InfomationViewController *vc = [[InfomationViewController alloc] init];
//            vc.changeIntroDelegate = self;
//            vc.type = @"1";
//            [self.navigationController pushViewController:vc animated:YES];
//        }
//    }
//}

- (void)changeImage {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *send = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.pickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        self.pickerController.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
        self.pickerController.cameraDevice = UIImagePickerControllerCameraDeviceRear;
        [self presentViewController:self.pickerController animated:YES completion:nil];
    }];
    UIAlertAction *get = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.pickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        self.pickerController.allowsEditing = YES;
        [self presentViewController:self.pickerController animated:YES completion:nil];
    }];
    
    [alert addAction:cancel];
    [alert addAction:send];
    [alert addAction:get];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)changeIntro:(NSString *)str withType:(NSString *)type {
    if ([type integerValue]) {
        [_tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:1 inSection:1]] withRowAnimation:UITableViewRowAnimationNone];
    }else {
        [_tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:1]] withRowAnimation:UITableViewRowAnimationNone];
    }
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    _headImage.image = image;
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self.pickerController dismissViewControllerAnimated:YES completion:nil];
}

@end
